package com.itheima.web.servlet;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import com.itheima.web.base.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends BaseServlet {
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1. 获取请求参数
            Map<String, String[]> map = request.getParameterMap();

            //2. 封装对象
            User user = new User();
            BeanUtils.populate(user, map);

            //3.调用service查询, 返回查询的User对象
            UserService service = new UserServiceImpl();
            User u = service.login(user);

            //4. 判断u对象是否存在
            if (u != null) {
                // 登录成功,用户名或密码正确
                request.getSession().setAttribute("user",u);
                response.sendRedirect(request.getContextPath()+"/index.jsp");

            }else{
                // 登录失败
                request.setAttribute("msg","用户名或密码错误!");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }


}
